package com.lanju.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Bills;
import com.lanju.entity.Server;
import com.lanju.entity.UserIdCard;


@Repository
public class BillsDao extends BaseDao<Bills,String>{
    
    private static final Log log = LogFactory.getLog(BillsDao.class);
    @Autowired
   	SessionFactory sessionFactory;
    
    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
	public List<Bills> queryBillsList(Map<String, Object> param) {
		   try {
			   int offset = Integer.parseInt( param.get("offset").toString() );
			   int limit = Integer.parseInt( param.get("limit").toString() );
			   StringBuffer sql=new StringBuffer();
			   sql.append("from Bills b where 1=1");
			   sql.append(" and  b.userId='"+param.get("userId").toString()+"'");
			   sql.append(" order by b.createTime desc") ;
				Query query=entityManager.createQuery(sql.toString());
				return query.setFirstResult(offset).setMaxResults(limit).getResultList();
	        } catch (Exception e) {
	            log.error("queryBillsList fail",e);
	            return null;
	        }
	}
    
	public long countBillsList(Map<String, Object> param) {
		 try {
			 StringBuffer sql=new StringBuffer();
			 sql.append("select count(*) from Bills b where 1=1");
			 sql.append(" and  b.userId='"+param.get("userId").toString()+"'");
			 Query query=entityManager.createQuery(sql.toString());
			 return (long) query.getSingleResult();
	        } catch (Exception e) {
	            log.error("countBillsList fail",e);
	        }
	        return 0;
	}

	public void deleteBills(Map<String, Object> param) {
		StringBuffer sql = new StringBuffer("delete from lj_bills ");
		sql.append(" where billsId = '"+param.get("id")+"'");
	    this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString()).executeUpdate();
	}

	public Map<String,Object> addService(Server server) {
		Map<String,Object> map=new HashMap<>();
		try {
			StringBuffer sql = new StringBuffer("insert into lj_service ");
			 if(!StringUtils.isEmpty(server.getServiceId())) {
				 sql.append("(serviceId");
			   }
			 if(!StringUtils.isEmpty(server.getServiceName())) {
				 sql.append(",serviceName");
			   }
			 if(!StringUtils.isEmpty(server.getServiceType())) {
				 sql.append(",serviceType");
			   }
			 if(!StringUtils.isEmpty(server.getServiceContent())) {
				 sql.append(",serviceContent");
			   }
			 if(!StringUtils.isEmpty(server.getServiceDesc())) {
				 sql.append(",serviceDesc");
			   }
			 if(!StringUtils.isEmpty(server.getCreator())) {
				 sql.append(",creator");
			   }
				 sql.append(",status");
			 if(!StringUtils.isEmpty(server.getTip())) {
				 sql.append(",tip");
			   }
			 if(!StringUtils.isEmpty(server.getChargesType())) {
				 sql.append(",chargesType");
			   }
			 sql.append(")values(");
			 if(!StringUtils.isEmpty(server.getServiceId())) {
				 sql.append("'"+server.getServiceId()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getServiceName())) {
				 sql.append(",'"+server.getServiceName()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getServiceType())) {
				 sql.append(",'"+server.getServiceType()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getServiceContent())) {
				 sql.append(",'"+server.getServiceContent()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getServiceDesc())) {
				 sql.append(",'"+server.getServiceDesc()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getCreator())) {
				 sql.append(",'"+server.getCreator()+"'");
			   }
				 sql.append(",1");
			 if(!StringUtils.isEmpty(server.getTip())) {
				 sql.append(",'"+server.getTip()+"'");
			   }
			 if(!StringUtils.isEmpty(server.getChargesType())) {
				 sql.append(",'"+server.getChargesType()+"'");
			   }
			 sql.append(")");
			 this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString()).executeUpdate();
			//entityManager.persist(server);
			map.put("result", true);	
			map.put("rows", server);
		} catch (Exception e) {
			map.put("result", false);
			e.printStackTrace();
		}
		return map;
	}

	public void updateService(Map<String, Object> param) {
		StringBuffer sql = new StringBuffer("update lj_service ");
		
		 if(!StringUtils.isEmpty(param.get("ServiceName"))) {
			 sql.append(" set serviceName = "+param.get("ServiceName")+"");
		   }
		 if(!StringUtils.isEmpty(param.get("serviceType"))) {
			 sql.append(" ,serviceType = "+param.get("serviceType")+"");
		   }
		 if(!StringUtils.isEmpty(param.get("serviceDesc"))) {
			 sql.append(" ,serviceDesc = "+param.get("serviceDesc")+"");
		   }
		 if(!StringUtils.isEmpty(param.get("serviceContent"))) {
			 sql.append(" ,serviceContent = "+param.get("serviceContent")+"");
		   }
		 if(!StringUtils.isEmpty(param.get("tip"))) {
			 sql.append(" ,tip = "+param.get("tip")+"");
		   }
		sql.append(" where serviceId = "+param.get("id")+"");
	    this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString()).executeUpdate();
		
	}

	public List<Map> queryDetailById(Map<String, Object> param) {
		 try {
			   StringBuffer sql=new StringBuffer();
			   sql.append(" select a.* from lj_bills a where 1=1");
			   sql.append(" and a.billsId = '"+param.get("id")+"'");
			   SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
			   return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	        } catch (Exception e) {
	            log.error("queryServiceDetailById fail",e);
	        }
		   return null;
	}

	public Map<String, Object> updateBills(String url,String id) {
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			StringBuffer sql = new StringBuffer("update lj_bills ");
			sql.append(" set imgUrl = '"+url+"'  where billsId = "+id+"");
			this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString()).executeUpdate();
			res.put("res", true);
		} catch (HibernateException e) {
			res.put("res", false);
			e.printStackTrace();
		}
		return res;
	}
	
	public void addIdCard(UserIdCard ui){
		try {
			entityManager.persist(ui);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	public List<Map> queryBillByUserId(Map<String, Object> param) {
		 try {
			   StringBuffer sql=new StringBuffer();
			   sql.append(" select a.* from lj_bills a where 1=1");
			   sql.append(" and a.userId = '"+param.get("userId")+"' and a.billType in ('1','2') and a.userType = '"+param.get("userType")+"'");
			   SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
			   return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	        } catch (Exception e) {
	            log.error("queryServiceDetailById fail",e);
	        }
		   return null;
	}
	
	public void addBills(Bills bills){
		try {
			entityManager.persist(bills);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
